//
//  AppDelegate.m
//  QuanJieShopProject
//
//  Created by apple on 2018/1/30.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "AppDelegate.h"

#import "QJTableVCManager.h"
#import <IQKeyboardManager.h>
//微信
#import "WXApiManager.h"
//支付宝
#import <AlipaySDK/AlipaySDK.h>
//友盟
//#import <UMCommon/UMCommon.h>

#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
//#import <BMKLocationkit/BMKLocationComponent.h>
//#import "BNCoreServices.h"

#import "SDImageCache.h"

#import "YFAppVersionUpdate.h"

@interface AppDelegate (){
    BMKGeoCodeSearch* _geocodesearch;
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.    
    [CLShareManager setShareAppKey];
    // 设置缓存大小 不起作用
//    [SDImageCache sharedImageCache].maxMemoryCost = 1024 * 1024 * 50;    // 50M
    NSUInteger tmpSize = [[SDImageCache sharedImageCache] getSize];
    if (tmpSize >= 1024 * 1024 * 60) { // 最大60M
//        [[SDImageCache sharedImageCache] clearMemory];
        // 都是存在磁盘上的, 不是在内存中
        [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    }
    
    //界面配置
    [self appPrepareAction];
    //微信支付
    [self payActionPrepare];
    
    // appStore检测是否有新版本
    YFAppVersionUpdate *update = [YFAppVersionUpdate sharedInstance];
    update.appID = @"1352793993";
    [update showAlertView];

    
    _mapManager = [[BMKMapManager alloc] init];
    /**
     *百度地图SDK所有接口均支持百度坐标（BD09）和国测局坐标（GCJ02），用此方法设置您使用的坐标类型.
     *默认是BD09（BMK_COORDTYPE_BD09LL）坐标.
     *如果需要使用GCJ02坐标，需要设置CoordinateType为：BMK_COORDTYPE_COMMON.
     */
    if ([BMKMapManager setCoordinateTypeUsedInBaiduMapSDK:BMK_COORDTYPE_BD09LL]) {
        KMyLog(@"经纬度类型设置成功");
    } else {
        KMyLog(@"经纬度类型设置失败");
    }
    // @"Mzs7DBNNpC7xKBIKQmwveNEQMs034Tpk"
    BOOL ret = [_mapManager start:@"Mzs7DBNNpC7xKBIKQmwveNEQMs034Tpk"  generalDelegate:self];
    if (ret) {
        KMyLog(@"key 设置成功了");
    }else {
        KMyLog(@"manager start failed!");
    }
    
    return YES;
}

- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        KMyLog(@"联网成功");
    }
    else{
        KMyLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        KMyLog(@"授权成功");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PermissionSuccess" object:nil];
    }
    else {
        KMyLog(@"onGetPermissionState %d",iError);
    }
}
#pragma mark -- App配置
- (void)appPrepareAction{
    //键盘配置
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    //有多个输入框时，可以通过点击Toolbar 上的“前一个” “后一个”按钮来实现移动到不同的输入框
    [IQKeyboardManager sharedManager].toolbarManageBehaviour = IQAutoToolbarByPosition;
    //tabbar
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[QJTableVCManager shareManager].managerVC];
    self.window.rootViewController = nav;
    [self.window makeKeyWindow];
    [self.window makeKeyAndVisible];
}

#pragma mark -- 支付功能配置
- (void)payActionPrepare{
    
    [WXApi registerApp:WXPay_ID];
    
}
#pragma mark -- 第三方用到的代理方法
//iOS9.0使用这个方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    //微信的支付回调
   
    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if(result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        /**
         *跳转支付宝钱包进行支付，处理支付结果
         */
        if([url.host isEqualToString:@"safepay"]) {
            
            [[AlipaySDK defaultService]processOrderWithPaymentResult:url standbyCallback:^(NSDictionary*resultDic) {
                if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                    //支付成功
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"alipaysuccsed" object:resultDic];
                }else{
                    //支付失败
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"alipayerror" object:resultDic];
                }
            }];
        }
        if([url.host isEqualToString:@"platformapi"]) {
            [[AlipaySDK defaultService]processOrderWithPaymentResult:url standbyCallback:^(NSDictionary*resultDic) {
                if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                    //支付成功
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"alipaysuccsed" object:resultDic];
                }else{
                    //支付失败
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"alipayerror" object:resultDic];
                }
            }];
        }
      
    }
    return YES;
    
}
//iOS9.0一下使用这个方法
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    //微信支付
    if ([WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]){
        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }else if ([url.host isEqualToString:@"safepay"]){
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                //支付成功
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipaysuccsed" object:resultDic];
            }else{
                //支付失败
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipayerror" object:resultDic];
            }
        }];
        return YES;
    }else{
        return YES;
    }
}
//所有系统使用的方法
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    //微信支付
    if ([WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]){
        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }else if ([url.host isEqualToString:@"safepay"]){
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                //支付成功
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipaysuccsed" object:resultDic];
            }else{
                //支付失败
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipayerror" object:resultDic];
            }
        }];
        return YES;
    }else{
        return YES;
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [self updateUserInfoAction];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}
#pragma mark -- 更新用户信息
- (void)updateUserInfoAction{
    BOOL isLogin = [QJUserInfo isLogin];
    if (isLogin) {
        
        [WWNetRequest fetchUserInfoWithParameters:nil success:^(id response) {
            NSLog(@"用户信息 response = %@", response);

            NSDictionary *infoDict = response[@"data"][@"userinfo"];
            if (response) {
                UpdateUserInfoModel *umodel = [[UpdateUserInfoModel alloc]initWithDictionary:infoDict error:nil];
                UserInfoModel *model = [QJUserInfo getCurrentUser];
                NSLog(@"umodel.user_type = %@", umodel.user_type);

                model.user_type = umodel.user_type;
                model.user_login = umodel.user_login;
                model.mobile = umodel.mobile;
                model.user_email = umodel.user_email;
                model.user_nickname = umodel.user_nickname;
                model.avatar = umodel.avatar;
                model.signature = umodel.signature;
                model.user_url = umodel.user_url;
                model.sex = umodel.sex;
                model.birthday = umodel.birthday;
                model.score = umodel.score;
                model.coin = umodel.coin;
                model.user_status = umodel.user_status;
                model.user_activation_key = umodel.user_activation_key;
                model.create_time = umodel.create_time;
                model.last_login_time = umodel.last_login_time;
                model.last_login_ip = umodel.last_login_ip;
                
                NSLog(@"token = %@", model.token);
                NSLog(@"user_type = %@", model.user_type);

            }
            
        } failure:^(NSDictionary *error) {
            NSLog(@"用户信息 error = %@", error);

        }];
    }
}

#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"QuanJieShopProject"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    KMyLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        KMyLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
